import { auths as _auths } from "./data.js";

let auths = _auths;

// //搜索权限
// const searchAuth = function (query) {
//   if(query.id === undefined && query.name === undefined) {
//     return auths;
//   } else {
//     let result = auths.filter(auth => auth.id === query.id || auth.name === query.name);
//     return result;
//   }
// };



// // 权限列表
// const getAuthList = function () {
//   return auths;
// };
// 权限列表
const getAuthList = function() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: auths,
        code: 0,
        msg: "请求成功",
      });
    }, Math.random() * 2000);
  });
};

// // 编辑权限
// const editAuth = function (id, detail) {
//   const copiedAuth = [...auths];
//   const target = auths.findIndex((c) => c.id === id);
//   if (copiedAuth[target]) {
//     copiedAuth[target] = detail;
//   }
// };

// 编辑权限
const editAuth = function(id, detail) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const copiedAuth = [...auths];
      const target = auths.findIndex((c) => c.id === id);
      if (copiedAuth[target]) {
        detail.name && (copiedAuth[target].name = detail.name);
        detail.describe && (copiedAuth[target].describe = detail.describe);
        //detail.status取值为0 短路 不赋值
        // detail.status && (copiedAuth[target].status = detail.status);
        copiedAuth[target].status = detail.status;
        detail.actions && (copiedAuth[target].actions = detail.actions);
        resolve({
          code: 0,
          data: null,
          msg: "修改成功",
        });
      } else {
        reject({
          code: 404,
          data: null,
          msg: "修改失败，id不存在",
        });
      }
    }, Math.random() * 2000);
  });
};

// // 新增权限
// const addAuth = function (newAuth) {
//   auths.unshift(newAuth);
// };
// 新增权限
const addAuth = function(newAuth) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      //将新数据添加到前边
      auths.unshift(newAuth);
      resolve({
        code: 0,
        data: null,
        msg: "添加成功",
      });
    }, Math.random() * 2000);
  });
};

// //删除权限
// const deleteAuth = function (id) {
//   auths = auths.filter(auth => auth.id !== id);
// };
// 删除权限

  const deleteAuth = function(id) {
    return new Promise((resolve, reject) => {
      const target = auths.find((c) => c.id === id);
      if (target) {
        const idx = auths.indexOf(target);
        auths.splice(idx, 1);
        // auths = auths.filter((c) => c.id !== id);
        console.log("api--------------------------删除", auths);
        resolve({
          code: 0,
          data: null,
          msg: "删除成功",
        });
      } else {
        reject({
          code: 404,
          data: null,
          msg: "删除失败，id不存在",
        });
      }
    });
  };

export { getAuthList, editAuth, addAuth, deleteAuth };
